package com.wk.wanjetpack.net

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.wk.base.START_PAGE
import com.wk.wanjetpack.bean.Article
import com.wk.wanjetpack.db.AppDataBase
import kotlinx.coroutines.delay
import retrofit2.HttpException
import java.io.IOException

/**
 * @author peng
 * @date 2021/1/25
 * 说明
 */
@ExperimentalPagingApi
class ArticleRemoteMediator(private val api: IApi) : RemoteMediator<Int, Article>() {
    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, Article>
    ): MediatorResult {
        try {
            val db = AppDataBase.instance
            val dao = db.articleDao

            val pageKey = when (loadType) {
                LoadType.REFRESH -> START_PAGE
                LoadType.PREPEND -> return MediatorResult.Success(true)
                LoadType.APPEND -> {
                    val item = state.lastItemOrNull() ?: return MediatorResult.Success(true)
                    item.pageIndex + 1
                }
            }

            delay(1000)
            val listData = api.getArticles(pageKey).data.datas
            listData.map { it.pageIndex = pageKey }
            db.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    dao.deleteAll()
                }
                dao.insertArticles(listData)
            }
            return MediatorResult.Success(listData.isEmpty())
        } catch (e: IOException) {
            return MediatorResult.Error(e)
        } catch (e: HttpException) {
            return MediatorResult.Error(e)
        }
    }
}